// home_tab_provider.dart
import 'package:app_router_demo/pages/home/models/home_list_model.dart';
import 'package:flutter/material.dart';
import '../services/http_service.dart';
import '../services/api_response.dart';

class HomeTabProvider with ChangeNotifier {
  late TabController _tabController;
  final List<String> _tabs = ['Recommend', 'New'];
  List<HomeTopCardModel> _cards = [];

  TabController get tabController => _tabController;
  List<String> get tabs => _tabs;
  List<HomeTopCardModel> get cards => _cards;

  HomeTabProvider({required TickerProvider vsync}) {
    _tabController = TabController(length: _tabs.length, vsync: vsync);
    _tabController.addListener(() {
      notifyListeners();
    });
    _fetchCardData();
  }

  Future<void> _fetchCardData() async {
    debugPrint('开始请求卡片数据...');
    try {
      final httpService = HttpService();
      // 如果 HttpService().initialize() 不在 main.dart 中，
      // 则需要确保在首次调用 httpService.get() 之前已经调用过 initialize()。
      // 简单起见，这里假设它已经在 main.dart 中被调用了。

      final ApiResponse<List<HomeTopCardModel>> response = await httpService
          .get<List<HomeTopCardModel>>(
            "/api/v1/home/home_shortcut_cards",
            fromJson: (jsonMap) {
              // 将参数名改为 jsonMap 更清晰，表示它是'data'字段的Map
              debugPrint('fromJson: 正在解析数据字段: $jsonMap');
              if (jsonMap is Map<String, dynamic> &&
                  jsonMap.containsKey('cards')) {
                final List<dynamic> cardsJson = jsonMap['cards'];
                debugPrint('fromJson: 发现cards列表: $cardsJson');
                try {
                  final List<HomeTopCardModel> parsedCards =
                      cardsJson
                          .map(
                            (e) => HomeTopCardModel.fromJson(
                              e as Map<String, dynamic>,
                            ),
                          )
                          .toList();
                  debugPrint('fromJson: 成功解析 ${parsedCards.length} 张卡片。');
                  return parsedCards;
                } catch (e) {
                  debugPrint('fromJson: 转换 HomeTopCardModel 失败: $e');
                  return null;
                }
              }
              debugPrint('fromJson: data字段不包含"cards"键，或不是Map类型。');
              return null; // 如果数据结构不符合预期，返回null
            },
          );

      debugPrint('API 响应的 success 状态: ${response.success}');
      debugPrint('API 响应的 message: ${response.message}');
      debugPrint('API 响应的 code: ${response.code}');
      debugPrint('API 响应的 data: ${response.data}'); // 这就是你看到的null

      if (response.success && response.data != null) {
        _cards = response.data!;
        debugPrint('成功获取卡片数据: ${_cards.length} 张卡片');
      } else {
        _cards = [];
        debugPrint('获取卡片数据失败或无数据。');
      }
    } catch (e) {
      _cards = [];
      debugPrint('请求卡片数据异常: $e');
      // 如果需要更详细的错误信息，可以打印DioException的类型或原始响应
      // if (e is DioException) {
      //   debugPrint('DioError: ${e.response?.data}');
      // }
    } finally {
      notifyListeners();
      debugPrint('请求卡片数据完成，UI已通知更新。');
    }
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
}
